<template>
  <div class="page-data pad">
    <div>
      <div class="head">
        <span>健康尺页面数据设置</span>
      </div>
    </div>
    <div v-if="!showSetting">
      <el-form inline>
        <el-form-item label="操作密码">
          <el-input v-model="password" clearable />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="confitmPassword" :loading="confirmPass">确定</el-button>
    </div>
    <el-tabs type="border-card" v-if="showSetting" @tab-click="tabClick">
      <el-tab-pane label="菜单项设置">
        <el-button type="primary" @click="openAddMenuDialog">添加菜单</el-button>
        <el-table :data="menuList" stripe border class="m-t-b" v-loading="tableLoading">
          <el-table-column label="菜单标题" prop="menuTitle"></el-table-column>
          <el-table-column label="菜单地址" prop="url"></el-table-column>
          <el-table-column label="菜单描述" prop="menuDescription"></el-table-column>
          <el-table-column label="菜单用途">
            <template slot-scope="scope">
              {{scope.row.menuType == 1 ? '健康尺' : (scope.row.menuType == 2 ? '消防' : '公用')}}
            </template>
          </el-table-column>
          <el-table-column label="菜单图标">
            <template slot-scope="scope">
              <img :src="scope.row.menuIcon" style="width: 40px; height: 40px" />
            </template>
          </el-table-column>
          <el-table-column label="菜单排序" prop="menuSort"></el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.enable"
                @change="changeStatus($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" circle @click="editMenu(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="习惯颜色设置">
        <el-button type="primary" @click="openAddHabit">添加习惯颜色</el-button>
        <el-table :data="habitColorList" stripe border class="m-t-b">
          <el-table-column label="色值1" prop="color1"></el-table-column>
          <el-table-column label="色值2" prop="color1"></el-table-column>
          <el-table-column label="预览">
            <template slot-scope="scope">
              <div
                class="color-preview"
                :style="{background: `linear-gradient(180deg, ${scope.row.color1} 0%, ${scope.row.color2} 100%)`}"
              ></div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                circle
                icon="el-icon-edit"
                @click="openEditHabitDialog(scope.row)"
              ></el-button>
              <el-button
                circle
                icon="el-icon-delete"
                type="danger"
                :loading="scope.row.loading"
                @click="deleteHabitColor(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="健康数据标签设置">
        <el-button type="primary" @click="openLabelDialog">添加标签</el-button>
        <el-table :data="labelList" stripe border class="m-t-b">
          <el-table-column label="标签名称" prop="labelTitle"></el-table-column>
          <el-table-column label="标签单位" prop="unit"></el-table-column>
          <el-table-column label="是否为默认项">
            <template slot-scope="scope">
              {{scope.row.isDefault ? '是' : '否'}}
            </template>
          </el-table-column>
          <el-table-column label="图标">
            <template slot-scope="scope">
              <img :src="scope.row.iconUrl" style="width: 20px; height: 20px;" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="changeLabelStatus($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit" @click="openLabelEdit(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="默认习惯设置">
        <el-button type="primary" @click="openAddHabitDialog">添加习惯</el-button>
        <el-table class="m-t-b" :data="habitList" stripe border v-loading="hLoading">
          <el-table-column label="习惯名称" prop="habitTitle"></el-table-column>
          <el-table-column label="习惯颜色色值" prop="habitColor"></el-table-column>
          <el-table-column label="习惯颜色预览">
            <template slot-scope="scope">
              <div
                class="color-preview"
                :style="{background: `linear-gradient(180deg, ${scope.row.color1} 0%, ${scope.row.color2} 100%)`}"
              ></div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                circle
                icon="el-icon-edit"
                @click="openEditDefaultHabitDialog(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
        class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleHabitPagi"
          :total="habitTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="结果评语设置">
        <el-button type="primary" @click="openAddCommentDialog">添加结果评语</el-button>
        <el-table :data="commentList" stripe border class="m-t-b" v-loading="commentLoading">
          <el-table-column label="性别">
            <template slot-scope="scope">
              {{scope.row.sex == '1' ? '男' : '女'}}
            </template>
          </el-table-column>
          <el-table-column label="年龄区间">
            <template slot-scope="scope">
              {{`${scope.row.minAge}岁 - ${scope.row.maxAge}岁`}}
            </template>
          </el-table-column>
          <el-table-column label="关联结果" prop="result"></el-table-column>
          <el-table-column label="结果评语" prop="bmiDesc"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit" @click="openUpdateCommentDialog(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCommentPagi"
          :total="commentTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :title="menuDialogTitle" :visible.sync="showMenuDialog">
      <el-form :model="menu" ref="menu" :rules="rules">
        <el-form-item label="菜单名称" prop="menuTitle">
          <el-input v-model="menu.menuTitle" />
        </el-form-item>
        <el-form-item label="菜单用途" prop="menuType">
          <el-radio-group v-model="menu.menuType">
            <el-radio :label="1">健康尺</el-radio>
            <el-radio :label="2">消防</el-radio>
            <el-radio :label="3">公用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单描述" prop="menuDescription">
          <el-input v-model="menu.menuDescription" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="menuIcon">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="uploadMenuIcon"
          >
            <img v-if="menu.menuIcon" :src="menu.menuIcon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="菜单排序" prop="menuSort">
          <el-input type="number" v-model="menu.menuSort" />
        </el-form-item>
        <el-form-item label="菜单页面地址" prop="url">
          <el-input v-model="menu.url" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveMenu" :loading="loading">{{isMenuEdit ? '保存更新' : '保存'}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="labelDialogTitle" :visible.sync="showLabelDialog">
      <el-form :model="label">
        <el-form-item label="标签名">
          <el-input v-model="label.labelTitle" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="label.unit" />
        </el-form-item>
        <el-form-item label="是否设为默认项">
          <el-switch
              active-text="是"
              inactive-text="否"
              v-model="isDefault"
              @change="changeDefault"
            ></el-switch>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="uploadItemsIcon"
          >
            <img v-if="label.iconUrl" :src="label.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveDataItem" :loading="labelLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="habitDialogTitle" :visible.sync="showHabitDialog">
      <el-form :model="habitColor">
        <el-form-item label="色值1">
          <el-input style="width: 100px;" type="color" v-model="habitColor.color1" />
        </el-form-item>
        <el-form-item label="色值2">
          <el-input style="width: 100px;" type="color" v-model="habitColor.color2" />
        </el-form-item>
        <el-form-item label="预览">
          <div
            class="color-preview"
            :style="{background: `linear-gradient(180deg, ${habitColor.color1} 0%, ${habitColor.color2} 100%)`}"
          ></div>
        </el-form-item>
        <el-form-item style="margin-left: 20px;">
          <el-button type="primary" @click="fetchAddHabitColor" :loading="habitLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="habitTitle" :visible.sync="showHabit">
      <el-form :model="habit" label-position="top">
        <el-form-item label="习惯名称">
          <el-input v-model="habit.habitTitle" />
        </el-form-item>
        <el-form-item label="习惯颜色">
          <el-select v-model="habit.habitColor">
            <el-option
              v-for="item in habitColorList"
              :key="item.colorId"
              :value="item.colorValue"
              :label="item.colorValue"
            ></el-option>
          </el-select>
          <div
            class="m-t-b"
            style="display: flex;"
            v-if="habit.habitColor"
          >
            <span style="padding-right: 20px;">颜色预览: </span>
            <div
              class="color-preview"
              :style="{background: `linear-gradient(180deg, ${habit.habitColor.split('-')[0]} 0%, ${habit.habitColor.split('-')[1]} 100%)`}"
            ></div>
          </div>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="saveHabit" :loading="addLoading">保存</el-button>
    </el-dialog>

    <el-dialog :title="commentDialogTitle" :visible.sync="showCommentDialog">
      <el-form :model="comment" label-position="top">
        <el-form-item label="性别">
          <el-select v-model="comment.sex">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄区间">
          <el-slider
            v-model="ageArea"
            range
            show-stops
            @change="changeAgeArea"
            :marks="marks"
            :max="100">
          </el-slider>
        </el-form-item>
        <el-form-item label="关联结果">
          <el-select v-model="comment.result">
            <el-option
              v-for="item in resultList"
              :key="item.resultId"
              :label="item.result"
              :value="item.result"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结果评语">
          <el-input type="textarea" rows="8" v-model="comment.bmiDesc" />
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        :loading="addCommentLoading"
        @click="saveComment"
      >保存</el-button>
    </el-dialog>
  </div>
</template>
<script>
import { fileToBase64, formatDate } from '../util';
import { uploadImage, updateLabelQuestion, getAllResultList } from '../api';
import axios from 'axios'
import {
  addFitbarMenuItem,
  getFitbarMenuItem,
  updateMenuItemStatus,
  addHabitColor,
  getHabitColorList,
  addHealthDataLabel,
  getHealthDataLabelList,
  updateDataLabelStatus,
  updateHomeMenu,
  updateHealthLabel,
  updateHabitColor,
  // testApi,
  deleteHabitColor,
  addDefaultHabit,
  getDefaultHabitList,
  updateDefaultHabit,
  addComment,
  getCommentListByPage,
  updateComment
} from '../api/version2';
export default {
  name: 'FitbarPageData',
  data () {
    return {
      menuDialogTitle: '添加菜单',
      showMenuDialog: false,
      password: '',
      loading: false,
      ageArea: [0, 15],
      habitLoading: false,
      confirmPass: false,
      showSetting: true,
      tableLoading: false,
      labelLoading: false,
      cHabitId: '',
      pageSize: 10,
      labelList: [],
      menuList: [],
      habitColorList: [],
      labelDialogTitle: '添加标签',
      showLabelDialog: false,
      showHabitDialog: false,
      habitDialogTitle: '添加习惯颜色',
      showHabit: false,
      hLoading: false,
      habitList: [],
      habitTotal: 0,
      addLoading: false,

      showCommentDialog: false,
      commentDialogTitle: '添加结果评语',
      commentList: [],
      commentTotal: 0,
      commentLoading: false,
      addCommentLoading: false,
      currentCommentId: '',
      comment: {
        result: '',
        sex: '',
        minAge: 0,
        maxAge: 15,
        bmiDesc: ''
      },
      resultList: [],
      marks: {
        0: '0岁',
        15: '15岁'
      },

      habitTitle: '添加默认习惯',
      habit: {
        habitTitle: '',
        habitColor: ''
      },

      isDefault: false,
      label: {
        labelTitle: '',
        unit: '',
        isDefault: 0,
        iconUrl: ''
      },
      menu: {
        menuTitle: '',
        menuDescription: '',
        menuIcon: '',
        menuSort: '',
        url: '',
        menuType: 1, // 1: 健康尺 2: 消防
      },
      currentMenuId: '',
      currentLabelId: '',
      currentHabitId: '',
      habitColor: {
        colorValue: '',
        color1: '',
        color2: '',
      },
      ad: {
        knowledgeId: '',
        advertisementPic: '',
        title: ''
      },
      isMenuEdit: false,
      rules: {
        menuTitle: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        menuDescription: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        menuIcon: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        menuSort: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openAddMenuDialog () {
       if (!this.$checkAuth('addMenu')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.menuDialogTitle = '添加菜单';
      this.resetMenu();
      this.showMenuDialog = true
    },
    openLabelDialog () {
      this.labelDialogTitle = '添加标签';
      this.label.labelTitle = '';
      this.label.unit = '';
      this.label.isDefault = 0;
      this.label.iconUrl = '';
      this.showLabelDialog = true;
    },
    testMethod () {
      testApi()
      .then(res => {
        console.log(res)
      })
    },
    openLabelEdit (row) { // 更新标签
      this.currentLabelId = row.labelId;
      this.label.labelTitle = row.labelTitle;
      this.label.unit = row.unit;
      this.label.isDefault = row.isDefault;
      this.isDefault = Boolean(row.isDefault);
      this.label.iconUrl = row.iconUrl;
      this.labelDialogTitle = '修改标签';
      this.showLabelDialog = true
    },
    openAddHabit () { // 打开添加习惯弹出框
       if (!this.$checkAuth('addHabitColor')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.habitDialogTitle = '添加习惯颜色';
      this.habitColor.colorValue = '';
      this.habitColor.color1 = '';
      this.habitColor.color2 = '';
      this.showHabitDialog = true
    },
    openEditHabitDialog (row) { // 打开编辑弹出框
       if (!this.$checkAuth('editHabitColor')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.currentHabitId = row.colorId;
      this.habitColor.colorValue = row.colorValue;
      this.habitColor.color1 = row.color1;
      this.habitColor.color2 = row.color2;
      this.habitDialogTitle = '修改习惯颜色';
      this.showHabitDialog = true
    },
    uploadMenuIcon ({ file }) {
      this.customUpload(file, 1)
    },
    uploadAdImg ({ file }) {
      this.customUpload(file, 3)
    },
    uploadItemsIcon ({ file }) {
      this.customUpload(file, 2)
    },
    changeDefault (e) {
      this.label.isDefault = Number(e)
    },
    customUpload (file, type) { // 上传图标
      const _this = this;
      fileToBase64(file, base64Str => {
        uploadImage(base64Str)
        .then(res => {
          let path = res.data.data.path;
          path = path.replace('http:', 'https:');
          if (type === 1) {
            _this.menu.menuIcon = path
          } else if (type === 2) {
            _this.label.iconUrl = path
          } else if (type === 3) {
            _this.ad.advertisementPic = path
          }
        })
        .catch(e => { })
      })
    },
    saveDataItem () { // 保存健康数据标签
      this.labelLoading = true;
      if (this.labelDialogTitle === '添加标签') {
        addHealthDataLabel(this.label)
        .then(res => {
          this.labelLoading = false;
          this.showLabelDialog = false;
          this.$message.success('创建成功!');
          this.fetchDataItems()
        })
        .catch(e => {
          this.showLabelDialog = false;
          this.labelLoading = false
        })
      } else {
        updateHealthLabel({
          ...this.label,
          labelId: this.currentLabelId
        })
        .then(res => {
          this.labelLoading = false;
          this.showLabelDialog = false;
          this.$message.success('修改成功!');
          this.fetchDataItems()
        })
        .catch(e => {
          this.showLabelDialog = false;
          this.labelLoading = false
        })
      }
    },
    changeLabelStatus (e, label) { // 改变状态
      this.$confirm(`确定 ${e ? '启用' : '禁用'} 标签${label.labelTitle}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        updateDataLabelStatus(label.labelId, Number(e))
        .then(res => {
          this.$message.success('操作成功');
          this.fetchDataItems()
        })
        .catch(e => {

        })
      })
      .catch(err => {
        label.enable = !e
      })
    },
    fetchDataItems () { // 查询数据表列表
      getHealthDataLabelList()
      .then(res => {
        let list = res.data.data || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'ZH');
          item.enable = Boolean(item.labelStatus)
        });
        this.labelList = list
      })
      .catch(e => {

      })
    },
    fetchAddHabitColor () { // 添加习惯颜色
      const { color1, color2 } = this.habitColor;
      if (!color1 || !color2) {
        return this.$message.error('请完善色值')
      };
      this.habitLoading = true;
      if (this.habitDialogTitle === '添加习惯颜色') { // 添加
        addHabitColor(`${color1}-${color2}`)
        .then(res => {
          this.$message.success('创建成功');
          this.habitLoading = false;
          this.showHabitDialog = false;
          this.fetchHabitColorList()
        })
        .catch(e => {
          this.showHabitDialog = false;
          this.habitLoading = false
        })
      } else { // 编辑
        updateHabitColor({
          colorId: this.currentHabitId,
          colorValue: `${color1}-${color2}`
        })
        .then(res => {
          this.$message.success('更新成功');
          this.habitLoading = false;
          this.showHabitDialog = false;
          this.fetchHabitColorList()
        })
        .catch(e => {
          this.habitLoading = false;
          this.showHabitDialog = false
        })
      }
    },
    saveMenu () { // 保存菜单
      this.$refs.menu.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.menuDialogTitle === '添加菜单') { // 添加
            addFitbarMenuItem(this.menu)
            .then(res => {
              this.loading = false;
              this.showMenuDialog = false;
              this.$message.success('创建成功');
              this.fetchMenuItems()
            })
            .catch(e => {
              this.showMenuDialog = false;
              this.loading = false
            })
          } else { // 编辑
            updateHomeMenu({
              ...this.menu,
              menuId: this.currentMenuId
            })
            .then(res => {
              this.loading = false;
              this.showMenuDialog = false;
              this.$message.success('更新成功');
              this.fetchMenuItems()
            })
            .catch(e => {
              this.showMenuDialog = false;
              this.loading = false
            })
          }
        } else {
          return false
        }
      })
    },
    fetchHabitColorList () { // 查询习惯颜色
      getHabitColorList()
      .then(res => {
        let list = res.data.data || [];
        console.log(list)
        list = list.filter(item => item.colorValue);
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'ZH');
          item.loading = false;
          item.color1 = item.colorValue.split('-')[0];
          item.color2 = item.colorValue.split('-')[1]
        });
        this.habitColorList = list;
        console.log('习惯颜色', list);
        console.log(this.habitColorList)
      })
      .catch(e => {})
    },
    confitmPassword () { // 确认密码
      if (!this.password.trim()) return;
      this.confirmPass = true;
      setTimeout(() => {
        if (this.password == '123456admin') {
        this.showSetting = true
        } else {
          this.$message.error('密码错误')
        };
        this.confirmPass = false
      }, 1000)
    },
    fetchMenuItems () { // 查询菜单项
      this.tableLoading = true;
      getFitbarMenuItem()
      .then(res => {
        this.tableLoading = false;
        const list = res.data.data || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'ZH');
          item.enable = Boolean(item.menuStatus)
        });
        this.menuList = list
      })
      .catch(e => {
        this.tableLoading = false
      })
    },
    changeStatus (e, row) { // 改变启用/禁用状态
       if (!this.$checkAuth('changeMenuStatus')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm(`确定 ${e ? '启用' : '禁用'} 菜单项 ${row.menuTitle}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        updateMenuItemStatus({
          menuId: row.menuId,
          menuStatus: Number(e)
        })
        .then(res => {
          this.$message.success('操作成功');
          this.fetchMenuItems()
        })
        .catch(e => {

        })
      })
      .catch(err => {
        row.enable = !e
      })
    },
    editMenu (row) { // 编辑菜单
      if (!this.$checkAuth('editMenu')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.currentMenuId = row.menuId;
      this.menu.menuTitle = row.menuTitle;
      this.menu.menuIcon = row.menuIcon;
      this.menu.menuDescription = row.menuDescription;
      this.menu.menuSort = row.menuSort;
      this.menu.url = row.url;
      this.menuDialogTitle = '编辑菜单';
      this.menu.menuType = row.menuType || 1;
      this.showMenuDialog = true
    },
    resetMenu () { // 重置菜单数据
      this.menu.menuTitle = '';
      this.menu.menuTitle = '';
      this.menu.menuIcon = '';
      this.menu.menuType = 1;
      this.menu.url = '';
      this.menu.menuDescription = ''
    },
    deleteHabitColor (habit) { // 删除颜色
       if (!this.$checkAuth('deleteColor')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm('确定删除该习惯颜色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        habit.loading = true;
        deleteHabitColor(habit.colorId)
        .then(res => {
          habit.loading = false;
          this.$message.success('操作成功');
          this.fetchHabitColorList()
        })
        .catch(e => {
          habit.loading = false
        })
      })
      .catch(err => {
        this.$message.info('取消删除')
      })
    },
    openAddHabitDialog () { // 添加默认习惯
      this.habit.habitColor = '';
      this.habit.habitTitle = '';
      this.showHabit = true
    },
    openEditDefaultHabitDialog (row) { // 打开编辑习惯框
      this.cHabitId = row.habitId;
      this.habit.habitTitle = row.habitTitle;
      this.habit.habitColor = row.habitColor;
      this.habitTitle = '修改默认习惯';
      this.showHabit = true

    },
    fetchDefaultHabitList (index) { // 查询默认习惯列表
      this.hLoading = true;
      getDefaultHabitList({
        index,
        count: this.pageSize
      })
      .then(res => {
        let list = res.data.data.list || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'zh:');
          item.color1 = item.habitColor.split('-')[0];
          item.color2 = item.habitColor.split('-')[1]
        });
        this.habitList = list;
        this.habitTotal = res.data.data.totalRecord;
        this.hLoading = false
      })
      .catch(e => {
        this.hLoading = false
      })
    },
    saveHabit () { // 保存习惯
      this.addLoading = true;
      if (this.habitTitle == '添加默认习惯') { // 添加
        addDefaultHabit(this.habit)
        .then(res => {
          this.addLoading = false;
          this.showHabit = false;
          this.$message.success('添加成功');
          this.fetchDefaultHabitList(1)
        })
        .catch(e => {
          this.addLoading = false
        })
      } else { // 修改
        updateDefaultHabit({
          ...this.habit,
          habitId: this.cHabitId
        })
        .then(res => {
          this.addLoading = false;
          this.showHabit = false;
          this.$message.success('修改成功');
          this.fetchDefaultHabitList(1)
        })
        .catch(e => {
          this.addLoading = false
        })
      }
    },
    handleHabitPagi (page) { // 习惯分页
      this.fetchDefaultHabitList(page)
    },
    fetchResultList () { // 查询结果列表
      getAllResultList()
      .then(res => {
        let list = res.data.data || [];
        list.unshift({
          resultId: -1,
          result: '正常'
        });
        this.resultList = list
      })
      .catch(e => {})
    },
    changeAgeArea (e) { // 改变年龄区间
      let obj = {};
      obj[e[0]] = e[0] + '岁';
      obj[e[1]] = e[1] + '岁';
      this.marks = obj;
      this.comment.minAge = e[0];
      this.comment.maxAge = e[1]
    },
    handleCommentPagi (page) { // 评语分页
      this.fetchCommentList(page)
    },
    openUpdateCommentDialog (row) { // 打开修改结果评语弹出框
      this.currentCommentId = row.bmiDescId;
      this.comment.sex = row.sex;
      this.comment.result = row.result;
      this.comment.minAge = row.minAge;
      this.comment.maxAge = row.maxAge;
      this.comment.bmiDesc = row.bmiDesc;
      this.ageArea = [row.minAge, row.maxAge];
      let obj = {};
      obj[row.minAge] = row.minAge + '岁';
      obj[row.maxAge] = row.maxAge + '岁';
      this.marks = obj;
      this.commentDialogTitle = '修改结果评语';
      this.showCommentDialog = true
    },
    saveComment () { // 保存评语
      this.addCommentLoading = true
      if (this.commentDialogTitle == '添加结果评语') { // 添加
        addComment(this.comment)
        .then(res => {
          this.$message.success('添加成功');
          this.addCommentLoading = false;
          this.showCommentDialog = false;
          this.fetchCommentList(1)
        })
        .catch(e => {
          this.addCommentLoading = false
        })
      } else { // 修改
        updateComment({
          bmiDescId: this.currentCommentId,
          ...this.comment
        })
        .then(res => {
          this.$message.success('修改成功');
          this.addCommentLoading = false;
          this.showCommentDialog = false;
          this.fetchCommentList(1)
        })
        .catch(e => {
          this.addCommentLoading = false
        })
      }
    },
    openAddCommentDialog () { // 打开添加评语弹出框
      this.commentDialogTitle = '添加结果评语';
      this.showCommentDialog = true
    },
    tabClick ({ index }) { // tab栏切换
      if (index == 4 && !this.commentList.length) {
        this.fetchCommentList(1)
      }
    },
    fetchCommentList (index) { // 查询评论列表
      this.commentLoading = true;
      getCommentListByPage({
        index,
        count: this.pageSize
      })
      .then(res => {
        let list = res.data.data.list || [];
        this.commentTotal = res.data.data.totalRecord;
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'zh:')
        });
        this.commentList = list;
        console.log(list)
        this.commentLoading = false
      })
      .catch(e => {
        this.commentLoading = false
      })
    }
  },
  created () {
    this.fetchMenuItems();
    this.fetchHabitColorList();
    this.fetchDataItems();
    this.fetchDefaultHabitList(1);
    this.fetchResultList()
  }
}
</script>
<style lang="scss">
  .color-preview {
    width: 77px;
    height: 30px;
    border-radius: 4px;
  }
</style>

